package com.can.service.impl;

import com.can.convert.UserConvert;
import com.can.domain.ResponseResult;
import com.can.domain.entity.LoginUser;
import com.can.domain.entity.User;
import com.can.domain.vo.BlogUserLoginVO;
import com.can.domain.vo.UserInfoVO;
import com.can.service.BlogLoginService;
import com.can.util.BeanCopyUtils;
import com.can.util.JwtUtil;
import com.can.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

import static com.can.constant.SystemConstants.BLOG_LOGIN_REDIS_PREFIX;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    // securityConfig中注入的
    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 默认是从内存中获取数据并认证,而我创建的UserDetailsServiceImpl实现了UserDetailsService,则变为了从数据库中进行查询并认证,同时会把查到信息封装为LoginUser封装进Authentication中的principal
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过(如果用户名不存在 或者 密码错误 都会返回 null)
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //把用户信息存入redis
        redisCache.setCacheObject(BLOG_LOGIN_REDIS_PREFIX + userId, loginUser);

        //把User转换成UserInfoVo,再把token和userinfo封装 返回
        UserInfoVO userInfoVO = UserConvert.INSTANCE.convert(loginUser.getUser());
        BlogUserLoginVO vo = new BlogUserLoginVO(jwt, userInfoVO);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject(BLOG_LOGIN_REDIS_PREFIX + userId);
        return ResponseResult.okResult();
    }

}